<!-- 
素材库页面使用 
-->
<template>
  <div>
    <a-modal
      :width="845"
      v-model:visible="props.visible"
      :maskClosable="false"
      title="上传素材"
      @cancel="cancel"
      :zIndex="1003"
    >
      <div class="filmitem_box">
        <!-- 图片 / 视频 / 音频 -->
        <div class="big-box" v-if="props.type !== 'text'">
          <!-- 上传组件-->
          <a-upload
            :disabled="loading || noenzu"
            class="model_upload"
            v-model:file-list="fileList"
            @drop="handleDrop"
            :customRequest="customRequest"
            :before-upload="beforeUpload"
            :multiple="true"
            name="file"
            :directory="directory"
            :accept="
              props.extension
                ? props.extension
                : props.type == 'video'
                ? accept.videoAccept
                : props.type == 'image'
                ? accept.imageAccept
                : props.type == 'audio'
                ? accept.audioAccept
                : `${accept.videoAccept},${accept.imageAccept},${accept.audioAccept}`
            "
          >
            <div class="model_upload_text">
              <div class="model_upload_top">
                <plus-outlined style="font-size: 16px; margin-right: 10px" />
                <div>从本地文件夹选择</div>
              </div>

              <div class="model_upload_bottom">
                <div v-if="props.type == 'video'">
                  支持的视频素材： mov/mp4/3gp（文件≤1G、时长≤60分钟）
                </div>
                <div v-if="props.type == 'image'">
                  图片格式：{{accept.imageAccept}}图片尺寸50~8000，单张图片不可大于20M
                </div>
                <div v-if="props.type == 'audio'">
                  音频格式：{{
                    props.extension
                      ? props.extension
                      : "mov/mp4/3gp（文件≤1G、时长≤60分钟）"
                  }}
                </div>
              </div>
            </div>
          </a-upload>

          <!-- 上传中-->
          <div class="isupdating" v-show="isupdate && isTen">
            <a-spin />
            <div>上传中</div>
          </div>

          <!-- 上传图片的预览 -->
          <div
            v-if="props.type == 'image'"
            class="updatevideo_All"
            v-for="(item, index) in updateImage"
            :key="index"
          >
            <div class="updatevideo_item" @click="previewClick(item)">
              <img :src="item.url" alt="" class="see_img" />
              <!-- 上传失败 -->
              <div class="up_fin" v-if="item.isfailed">
                <a-tag color="red">上传失败</a-tag>
              </div>

              <!-- 已上传 -->
              <div class="up_fin" v-if="item.up_finish == true">
                <a-tag color="success">已上传</a-tag>
              </div>
            </div>
            <!-- 进度条  上传中-->
            <div class="progress_item" v-if="item.up_ing == true">
              <a-progress
                :percent="isAlionline || isOss ? item.uploadProgress : 100"
                :showInfo="isAlionline || isOss"
                type="line"
                size="small"
                :stroke-color="{
                  '0%': '#108ee9',
                  '100%': '#87d068',
                }"
                status="active"
              />
            </div>

            <div class="updatevideo_bottom">
              <div class="updatevideo_bottom_left">
                {{ item.name }}
              </div>

              <div class="updatevideo_bottom_right">
                <delete-outlined
                  v-if="!loading"
                  class="updatevideo_icon_right"
                  @click="del_upImage(index)"
                />
              </div>
            </div>
          </div>

          <!-- 上传视频的预览 -->
          <div
            v-if="props.type == 'video'"
            class="updatevideo_All"
            v-for="(item, index) in updatevideo"
            :key="index"
          >
            <div class="updatevideo_item" @click="previewClick(item)">
              <video
                :id="item.id"
                class="updatevideo_item_s"
                :src="item.url"
              ></video>

              <!-- 已上传 -->
              <div class="up_fin" v-if="item.up_finish == true">
                <a-tag color="success">已上传</a-tag>
              </div>

              <!-- 上传失败 -->
              <div class="up_fin" v-if="item.isfailed">
                <a-tag color="red">上传失败</a-tag>
              </div>
            </div>

            <!-- 进度条  上传中   :percent="item.uploadProgress"-->
            <div class="progress_item" v-if="item.up_ing == true">
              <a-progress
                :percent="isAlionline || isOss ? item.uploadProgress : 100"
                :showInfo="isAlionline || isOss"
                type="line"
                size="small"
                :stroke-color="{
                  '0%': '#108ee9',
                  '100%': '#87d068',
                }"
                status="active"
              />
            </div>

            <div class="updatevideo_bottom">
              <div class="updatevideo_bottom_left">
                {{ item.name }}
              </div>

              <div class="updatevideo_bottom_right">
                <delete-outlined
                  v-if="!loading"
                  class="updatevideo_icon_right"
                  @click="del_up(index)"
                />
              </div>
            </div>
          </div>

          <!-- 上传音频的预览 -->
          <div
            v-if="props.type == 'audio'"
            class="updatevideo_All"
            v-for="(item, index) in updateAudio"
            :key="index"
          >
            <div class="updatevideo_item" @click="previewClick(item)">
              <cu-icon
                type="icon-audio"
                style="font-size: 40px; display: flex; align-items: center"
              />

              <!-- 已上传 -->
              <div class="up_fin" v-if="item.up_finish == true">
                <a-tag color="success">已上传</a-tag>
              </div>

              <!-- 上传失败 -->
              <div class="up_fin" v-if="item.isfailed">
                <a-tag color="red">上传失败</a-tag>
              </div>
            </div>

            <!-- 进度条  上传中-->
            <div class="progress_item" v-if="item.up_ing == true">
              <a-progress
                :percent="isAlionline || isOss ? item.uploadProgress : 100"
                :showInfo="isAlionline || isOss"
                type="line"
                size="small"
                :stroke-color="{
                  '0%': '#108ee9',
                  '100%': '#87d068',
                }"
                status="active"
              />
            </div>

            <div class="updatevideo_bottom">
              <div class="updatevideo_bottom_left">
                {{ item.name }}
              </div>

              <div class="updatevideo_bottom_right">
                <delete-outlined
                  v-if="!loading"
                  class="updatevideo_icon_right"
                  @click="del_upaudio(index)"
                />
              </div>
            </div>
          </div>
        </div>

        <!-- 文案 -->
        <template v-else>
          <div class="text-content hide-scroller-bar">
            <a-row
              v-for="(user, index) in dynamicValidateForm.users"
              :key="index"
              align="middle"
              :gutter="[16, 16]"
            >
              <a-col flex="1">
                <a-form layout="vertical" :model="dynamicValidateForm">
                  <a-form-item
                    label="文案:"
                    :name="['users', index, 'name']"
                    :rules="{
                      required: true,
                      message: '请输入文案',
                    }"
                  >
                    <a-textarea
                      v-model:value="user.name"
                      show-count
                      :maxlength="5000"
                      :rows="4"
                      placeholder="请输入文案"
                    />
                  </a-form-item>
                </a-form>
              </a-col>
              <a-col>
                <div>
                  <a-button type="primary" class="btn_btn" @click="addForm"
                    >新增</a-button
                  >
                </div>
                <div>
                  <a-button
                    type="primary"
                    class="btn_btn"
                    v-if="dynamicValidateForm.users.length > 1"
                    @click="removeUser(user)"
                    >删除</a-button
                  >
                </div>
              </a-col>
            </a-row>
          </div>
        </template>
      </div>

      <template #footer>
        <a-button
          v-if="props.type == 'text'"
          key="submit"
          type="primary"
          :disabled="isNameEmpty"
          :loading="loading"
          @click="saveFn"
          >确定</a-button
        >
        <a-button
          v-if="props.type !== 'text'"
          key="submit"
          type="primary"
          :disabled="!queryData.files.length"
          :loading="loading"
          @click="saveFn"
          >开始上传</a-button
        >
      </template>

      <!-- 预览弹框 -->
      <PreviewModal
        :visible="visiblePreview"
        :title="fileData.name"
        :url="fileData.url"
        :type="props.type"
        @onCancel="visiblePreview = false"
      />

      <!-- 确认关闭-->
      <CancelModal
        :visible="visiblecancel"
        @onCancel="visiblePreview = false"
      />
    </a-modal>
  </div>
</template>

<script setup>
import {
  reactive,
  watch,
  ref,
  computed,
  defineProps,
  defineEmits,
  createVNode,
  onMounted,
  onUnmounted,
} from "vue";
import request from "@/common/utils/request";
import utils from "@/common/utils/utils.js";
import PreviewModal from "../../../../components/PreviewModal/index.vue";
import store from "../../../../store/index.js";
import axios from "axios";
import defaultSetting from "@/common/utils/defaultSetting.js";

import { upload } from "@/common/utils/uploader/index";
import {
  InfoCircleOutlined,
  DeleteOutlined,
  ExclamationCircleOutlined,
  PlusOutlined,
} from "@ant-design/icons-vue";
import { message, Modal, notification } from "ant-design-vue";
import {accept}from '@/common/utils/atherUtils.js'


const emits = defineEmits(["onSubmit", 'topUp']);

const props = defineProps({
  type: {
    type: String,
    default: "",
  },
  visible: {
    type: Boolean,
    default: false,
  },
  group_id: {
    type: String,
    default: "",
  },
  optionsDetail: {
    type: Object,
    default: {},
  },
  Updateb_name: {
    type: String,
    default: "",
  },
  fileData: {
    type: Object,
    default: () => {
      return {};
    },
  },
  extension: {
    type: String,
    default: "",
  },
});
// TODO 上传素材弹窗

const fileList = ref([]);
const isupdate = ref(false);

const updatevideo = ref([]);
const updateImage = ref([]);
const updateAudio = ref([]);
const loading = ref(false);
const ReUpload = ref([]);

const work_ai_config = computed(() => {
  return store?.state?.shotstack?.work_ai_config || {};
});

const isAlionline = computed(() => {
  return work_ai_config.value?.shotstack_driver == "alionline";
});

const isOss = computed(() => {
  return work_ai_config.value?.upload_driver == "oss";
});

const updateData = ref({
  scene: "",
  merchant_folder_statck_id: "",
  org_id: utils.getOrgId(),
  user_token: utils.getToken(),
  cur_env: utils.isMobile()
    ? "h5"
    : import.meta.env.ELECTRON
    ? "desktop"
    : "pc",
  team_id: utils.getCurrentTeam(),
  dir: "work_ai",
});

const queryData = ref({
  files: [],
});
const fileType = ref("");

const getFileType = (file) => {
      // 如果 file.type 不为空，直接返回
      if (file.type) return file.type;

      // 基于扩展名推测 MIME 类型
      const extension = file.name.split('.').pop().toLowerCase();
      const mimeTypes = {
        mov: 'video/quicktime',
        mp4: 'video/mp4',
        '3gp': 'video/3gpp',
        jpg: 'image/jpeg',
        jpeg: 'image/jpeg',
        png: 'image/png',
        mp3: 'audio/mpeg',
        m4a: 'audio/mp4',
        wav: 'audio/wav',
        ogg: 'audio/ogg',
        pcm: 'audio/pcm',
      };
      return mimeTypes[extension] || '';
    };

const customRequest = (file) => {
  const isDuplicate = queryData.value.files.some(
    (existingFile) => existingFile.name === file.file.name
  );
  if (isDuplicate) {
    return message.warning("请勿重复上传文件！");
  }
  queryData.value.files.push(file.file);



  fileType.value = getFileType(file.file).split("/")[0];
  if (fileType.value == "image") {
    // 图片类型
    const url = URL.createObjectURL(file.file);
    updateImage.value.push({
      url: url,
      name: file.file.name,
      id: file.file.uid,
      up_ing: false,
      up_finish: false,
      uploadProgress: 0,
      isfailed: false,
    });
  } else if (fileType.value == "video") {
    const url = URL.createObjectURL(file.file);
    updatevideo.value.push({
      url: url,
      name: file.file.name,
      id: file.file.uid,
      isplayshow: true,
      up_ing: false,
      up_finish: false,
      uploadProgress: 0,
      isfailed: false,
    });
  } else if (fileType.value == "audio") {
    const url = URL.createObjectURL(file.file);
    updateAudio.value.push({
      url: url,
      name: file.file.name,
      id: file.file.uid,
      up_ing: false,
      up_finish: false,
      uploadProgress: 0,
      isfailed: false,
    });
  }
};

const ALLshouldContinuePolling = ref(true);
const isAll_upload = ref(false);

const is_over = ref(false);

const BASE_URL = ref("");

// 保存接口
const saveFn = async () => {
  if (props.type !== "text") {
    if (!queryData.value.files.length) {
      message.warn("请上传素材");
      return;
    }

    loading.value = true;
    // 定义上传队列
    const uploadQueue = [];
    const MAX_CONCURRENT_UPLOADS = 3;

    BASE_URL.value = defaultSetting.requestDomain;
    if (process.env.NODE_ENV === "development") {
      BASE_URL.value = BASE_URL.value + "/api";
    }

    // 检查剩余空间并上传文件
    function uploadFile(file, index) {
      return new Promise((resolve, reject) => {
        request
          .post("/work_ai", "/material/get/capacity")
          .then((res) => {
            const remainingCapacity = parseInt(res.result.remainingCapacity, 10);
            console.log(remainingCapacity,'剩余空间', file.size);
            
            if (remainingCapacity < file.size) {
              // 内存不够
              message.error(`存储空间不足，无法上传文件：${file.name}`);
              resolve(); // 释放队列中的位置
            } else {
              // 内存够 发起请求
              const formData = new FormData();
              formData.append("file", file);
              formData.append("type", fileType.value);
              formData.append("scene", fileType.value);
              formData.append("merchant_folder_statck_id", props.fileData.id);
              formData.append("org_id", utils.getOrgId());
              formData.append("user_token", utils.getToken());
              formData.append(
                "cur_env",
                utils.isMobile()
                  ? "h5"
                  : import.meta.env.ELECTRON
                  ? "desktop"
                  : "pc"
              );
              formData.append("team_id", utils.getCurrentTeam());
              formData.append("path_synchronous", "1");

              axios({
                method: "post",
                url: `${BASE_URL.value}/work_ai/material/upload`,
                data: formData,
                headers: {
                  "Content-Type": "multipart/form-data",
                  "Org-Token": utils.getToken(),
                },
              })
                .then((response) => {
                  if (response?.data?.data?.errorData.length > 0) {
                    // 错误处理
                    notification.warn({
                      message: response.data.data.errorData[0],
                      duration: 2,
                    });
                    resolve(); // 释放队列中的位置
                  } else {
                    handleUploadSuccess(response, index)
                      .then(resolve)
                      .catch(reject);
                  }
                })
                .catch(reject);
            }
          })
          .catch(reject);
      });
    }

    // 处理上传成功的逻辑
    async function handleUploadSuccess(response, index) {
      switch (props.type) {
        case "image":
          updateImage.value[index].up_ing = true;
          break;
        case "video":
          updatevideo.value[index].up_ing = true;
          break;
        case "audio":
          updateAudio.value[index].up_ing = true;
          break;
      }

      let pollInterval; // 用于存储setInterval的返回值，以便稍后清除
      let shouldContinuePolling = true; // 控制是否继续轮询的标志

      // 开始轮询
      pollInterval = setInterval(async () => {
        if (!ALLshouldContinuePolling.value) {
          clearInterval(pollInterval); // 如果应停止轮询，则清除定时器
          return;
        }
        if (!shouldContinuePolling) {
          clearInterval(pollInterval); // 如果应停止轮询，则清除定时器
          return;
        }

        await request
          .get("/work_ai", "/material/upload/status", {
            taskId: response.data.data.returnData[0].taskId,
          })
          .then(async (res) => {
            if (res.status === 1) {
              // 继续轮询
            } else if (res.status === 2) {
              shouldContinuePolling = false; // 设置标志以停止轮询
              clearInterval(pollInterval); // 清除定时器

              await markUploadComplete(index);
            } else if (res.status === 3) {
              // 上传失败  停止轮训
              shouldContinuePolling = false; // 设置标志以停止轮询
              message.error("上传失败");
              clearInterval(pollInterval); // 清除定时器
            }
          })
          .catch((error) => {
            clearInterval(pollInterval);
          });
      }, 2000);

      return new Promise((resolve) => {
        // 一旦完成上传，调用resolve
        setTimeout(resolve, 5000); // 这里只是一个示例，实际上应该在上传完成后调用resolve
      });
    }

    // 标记上传完成
    async function markUploadComplete(index) {
      switch (props.type) {
        case "image":
          updateImage.value[index].up_ing = false;
          updateImage.value[index].up_finish = true;
          if (updateImage.value.every((item) => item.up_finish === true)) {
            // 全部上传成功
            emits("onSubmit");
            message.success("上传成功");
            updateImage.value = [];
            loading.value = false;
            isupdate.value = false;
            queryData.value.files = [];
          }
          break;
        case "video":
          updatevideo.value[index].up_ing = false;
          updatevideo.value[index].up_finish = true;
          if (updatevideo.value.every((item) => item.up_finish === true)) {
            // 全部上传成功
            emits("onSubmit");
            message.success("上传成功");
            updatevideo.value = [];
            loading.value = false;
            isupdate.value = false;
            queryData.value.files = [];
          }
          break;
        case "audio":
          updateAudio.value[index].up_ing = false;
          updateAudio.value[index].up_finish = true;
          if (updateAudio.value.every((item) => item.up_finish === true)) {
            // 全部上传成功
            emits("onSubmit");
            message.success("上传成功");
            updateAudio.value = [];
            loading.value = false;
            isupdate.value = false;
            queryData.value.files = [];
          }
          break;
      }
    }

    // Cos上传
    async function startUploads() {
      console.log("cos上传");
      for (let i = 0; i < queryData.value.files.length; i++) {
        const file = queryData.value.files[i];
        // 将上传任务添加到队列中
        uploadQueue.push(uploadFile(file, i));

        // 如果队列中的任务数量超过了最大并发数，等待队列中的一个任务完成
        if (uploadQueue.length > MAX_CONCURRENT_UPLOADS) {
          await uploadQueue.shift();
        }
      }

      // 等待所有上传任务完成
      await Promise.all(uploadQueue);
    }

    // 控制并发数量的函数
    async function processQueue(queue, concurrency) {
      const runningTasks = new Set(); // 使用Set来存储正在运行的任务
      const results = [];

      const addTask = async () => {
        if (queue.length === 0) {
          return; // 如果队列为空，则不再添加新任务
        }

        const task = queue.shift();
        const promise = task()
          .then((res) => {
            if (res == undefined) {
              res = false;
            }
            results.push(res);
            runningTasks.delete(promise); // 任务完成后从集合中删除
            addTask(); // 尝试添加下一个任务
          })
          .catch((error) => {
            results.push(null); // 记录失败的结果
            runningTasks.delete(promise); // 任务完成后从集合中删除
            addTask(); // 尝试添加下一个任务
          });

        runningTasks.add(promise); // 添加到正在运行的任务集合中
      };

      // 初始填充运行任务
      for (let i = 0; i < concurrency; i++) {
        addTask();
      }
      // 等待所有任务完成
      while (runningTasks.size > 0 || queue.length > 0) {
        await Promise.race(runningTasks);
      }

      return results;
    }

    let oss_config;

    let refreshTimeout;
    async function getOss_config() {
      const response = await request.post(
        "/work_ai",
        "/upload/oss/config/ststoken",
        {
          isRefresh: "1",
        }
      );
      if (response.sts) {
        oss_config = response.sts;
        const duration = response.sts.duration;
        const refreshTime = (duration - 5 * 60) * 1000;
        refreshTimeout = setTimeout(getOss_config, refreshTime);

        const nowTimestamp = Date.now();

        const expiresAtTimestamp = nowTimestamp + response.sts.duration * 1000;
        const stsToken_config = {
          stsToken: response.sts.stsToken,
          duration: response.sts.duration,
          FailDate: expiresAtTimestamp,
        };

        localStorage.setItem(
          "stsToken_config",
          JSON.stringify(stsToken_config)
        );
      } else {
        const Reres = await request.post(
          "/work_ai",
          "/upload/oss/config/ststoken",
          {
            isRefresh: "1",
          }
        );
        oss_config = Reres.sts;
        const duration = Reres.sts.duration;
        const refreshTime = (duration - 5 * 60) * 1000;
        refreshTimeout = setTimeout(getOss_config, refreshTime);
      }
    }

    async function RegetOss_config() {
      const response = await request.post(
        "/work_ai",
        "/upload/oss/config/ststoken",
        {
          isRefresh: "1",
        }
      );
      if (response.sts) {
        oss_config = response.sts;
        const nowTimestamp = Date.now();
        const expiresAtTimestamp = nowTimestamp + response.sts.duration * 1000;
        const stsToken_config = {
          stsToken: response.sts.stsToken,
          duration: response.sts.duration,
          FailDate: expiresAtTimestamp,
        };

        localStorage.setItem(
          "stsToken_config",
          JSON.stringify(stsToken_config)
        );
      }
    }

    // Oss上传
    async function startOssUploads() {
      await getOss_config();

      const newoss_config = JSON.parse(localStorage.getItem("stsToken_config"));

      // token 过期处理
      if (newoss_config == null) {
        await RegetOss_config();
      }
      const nowTime = Date.now();

      if (newoss_config.FailDate < nowTime) {
        await RegetOss_config();
      }

      let upDataList = queryData.value.files.map((item) => ({
        ...item,
        name: item.name,
        id: item.uid,
        state: 0,
        percent: 0,
        iscancel: false,
      }));
      // 将上传数据 同步至vuex
      store.dispatch("SetUpDateList", upDataList);

      const uploadQueue = queryData.value.files.map((file, i) => async () => {
        switch (props.type) {
          case "image":
            updateImage.value[i].up_ing = true;
            break;
          case "video":
            updatevideo.value[i].up_ing = true;
            break;
          case "audio":
            updateAudio.value[i].up_ing = true;
            break;
        }
        // 可选的配置对象
        const config = {
          SetUploadPath: SetUploadPath.value,
          oss_config: oss_config,
        };

        const res = await upload(file, config);

        if (res.state == false) {
          switch (props.type) {
            case "image":
              updateImage.value.forEach((v1) => {
                if (v1.name == res.name) {
                  v1.up_ing = false;
                  v1.up_finish = true;
                  v1.isfailed = true;
                }
              });
              if (updateImage.value.every((item) => item.up_finish == true)) {
                isAll_upload.value = true;
              }
              break;
            case "video":
              updatevideo.value.forEach((v1) => {
                if (v1.name == res.name) {
                  v1.up_ing = false;
                  v1.up_finish = true;
                  v1.isfailed = true;
                }
              });
              if (updateImage.value.every((item) => item.up_finish == true)) {
                isAll_upload.value = true;
              }
              break;
            case "audio":
              updateAudio.value.forEach((v1) => {
                if (v1.name == res.name) {
                  v1.up_ing = false;
                  v1.up_finish = true;
                  v1.isfailed = true;
                }
              });
              if (updateImage.value.every((item) => item.up_finish == true)) {
                isAll_upload.value = true;
              }
              break;
          }
        }

        if (res.fileUrl) {
          let up_paramas = {
            merchant_folder_statck_id: props.fileData.id,
            material_type: props.type,
            material_name: file.name,
            material_url: res.fileUrl,
            material_size: file.size,
          };

          if (!is_over.value) {
            try {
              const response = await request.post(
                "/work_ai",
                "/user/mobile/media",
                up_paramas
              );

              switch (props.type) {
                case "image":
                  updateImage.value.forEach((v1) => {
                    if (v1.name == file.name) {
                      v1.up_ing = false;
                      v1.up_finish = true;
                    }
                  });

                  if (
                    updateImage.value.every((item) => item.up_finish == true)
                  ) {
                    isAll_upload.value = true;
                  }
                  break;
                case "video":
                  updatevideo.value.forEach((v1) => {
                    if (v1.name == file.name) {
                      v1.up_ing = false;
                      v1.up_finish = true;
                    }
                  });

                  let successData = store.state.user.updataList.map((item) => ({
                    ...item,
                    name: item.name,
                    id: item.uid,
                    success: "上传成功",
                    percent: 100,
                  }));

                  store.dispatch("SetUpDateList", successData);

                  if (
                    updatevideo.value.every((item) => item.up_finish == true)
                  ) {
                    isAll_upload.value = true;
                  }

                  break;
                case "audio":
                  updateAudio.value.forEach((v1) => {
                    if (v1.name == file.name) {
                      v1.up_ing = false;
                      v1.up_finish = true;
                    }
                  });

                  if (
                    updateAudio.value.every((item) => item.up_finish == true)
                  ) {
                    isAll_upload.value = true;
                  }
                  break;
              }

              return response;
            } catch (error) {
              message.error("上传错误, 请稍后重试");
              // 上传失败的 处理
              switch (props.type) {
                case "image":
                  updateImage.value.forEach((v1) => {
                    if (v1.name == file.name) {
                      v1.up_ing = false;
                      v1.isfailed = true;
                    }
                  });
                  break;
                case "video":
                  updatevideo.value.forEach((v1) => {
                    if (v1.name == file.name) {
                      v1.up_ing = false;
                      v1.isfailed = true;
                    }
                  });
                  break;
                case "audio":
                  updateAudio.value.forEach((v1) => {
                    if (v1.name == file.name) {
                      v1.up_ing = false;
                      v1.isfailed = true;
                    }
                  });
                  break;
              }
              return null;
            }
          }
        }
      });

      const results = await processQueue(uploadQueue, 2); // 限制并发数量为2

      if (results.every((res) => res?.result) && isAll_upload.value) {
        isUploadComplete.value = true;
        updatevideo.value = [];
        updateImage.value = [];
        updateAudio.value = [];
        isupdate.value = false;
        queryData.value.files = [];
        message.success("上传完成!");
        loading.value = false;
        emits("onSubmit");
      }

      if (isAll_upload.value && results) {
        isUploadComplete.value = true;
        updatevideo.value = [];
        updateImage.value = [];
        updateAudio.value = [];
        isupdate.value = false;
        queryData.value.files = [];
        // message.success("部分上传失败, 请稍后重试!");
        loading.value = false;
        emits("onSubmit");
      }
    }
    if (isAlionline.value || isOss.value) {
      // 阿里云上传
      startOssUploads();
    } else {
      startUploads();
    }
  } else {
    let isAllEmpty = dynamicValidateForm.users.every(
      (item) => item.name.trim().length > 0
    );
    if (!isAllEmpty) {
      return message.error("请输入文案");
    } else {
      //文案上传
      let params = {
        merchant_folder_statck_id: props.fileData.id,
        material_type: props.type,
        headline: dynamicValidateForm.users.map((item) => item.name),
      };
      loading.value = true;
      request
        .post("/work_ai", "/user/shotstack/text", params)
        .then((res) => {
          if (res.result) {
            message.success("添加成功");
            emits("onSubmit", "text");
            loading.value = false;
            dynamicValidateForm.users = [{ name: "" }];
          }
          loading.value = false;
        })
        .catch((err) => {
          loading.value = false;
        });
    }
  }
};

const SetUploadPath = ref("");
// 上传前的准备
const beforeUpload = async (file) => {
  if (props.type === "video") {
    return new Promise((resolve) => {
      const isLt1G = file.size / 1024 / 1024 / 1024 < 1;
      if (free_send_text.value && free_send_text.value == "赠送套餐") {
        if (file.size > fileMaxSize.value) {
          message.error(fileMaxSizeErr.value);
          resolve(false);
          return;
        }
      }
      if (!isLt1G) {
        message.error("视频文件不可大于 1GB!");
        resolve(false);
        return;
      }
      const video = document.createElement("video");
      const blobURL = URL.createObjectURL(file);
      video.src = blobURL;
      video.onloadedmetadata = () => {
        const duration = video.duration;
        const width = video.videoWidth;
        const height = video.videoHeight;

        if (duration > 3600) {
          message.error("视频文件不能大于 60 分钟时长!");
          resolve(false);
          return;
        }


        if (width > 4096 || height > 4096) {
          message.error("视频最大不能超过 4096px!");
          resolve(false);
          return;
        }

        resolve(true);
      };

      updateData.value.scene = props.type;
      updateData.value.merchant_folder_statck_id = props.fileData.id;
      ReUpload.value.push(file.uid);
    });
  } else if (props.type == "image") {
    const isLt2M = file.size / 1024 / 1024 < 20;

    if (free_send_text.value && free_send_text.value == "赠送套餐") {
      if (file.size > fileMaxSize.value) {
        message.error(fileMaxSizeErr.value);
        resolve(false);
        return;
      }
    }

    let w = 0,
      h = 0;
    let reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => {
      const image = new Image();
      image.src = reader.result;
      image.onload = () => {
        w = image.width;
        h = image.height;
        if (w <= 49 || h <= 49) {
          state.fileList = state.fileList.filter(
            (item) => item.uid !== file.uid
          );
          message.error("图片宽度不能小于50px");
          return false;
        } else if (w >= 8000 || h >= 8000) {
          state.fileList = state.fileList.filter(
            (item) => item.uid !== file.uid
          );
          message.error("图片宽度不能大于8000px");
          return false;
        }
        if (!isLt2M) {
          message.error("文件不可大于 20M!");
          return false;
        }
        return true;
      };
    };
    updateData.value.scene = props.type;
    updateData.value.merchant_folder_statck_id = props.fileData.id;
    ReUpload.value.push(file.uid);
  }
};

// 取消
const cancel = () => {
  if (loading.value) {
    if (!isAlionline.value && !isOss.value) {
      message.error("正在上传中");
    } else {
      emits("cancel");
    }
  } else {
    emits("cancel");
  }
};

// 删除预览
const del_up = (index) => {
  updatevideo.value.forEach((item) => {
    const videoElement = document.getElementById(item.id);
    if (videoElement) {
      videoElement.pause();
      item.isplayshow = true;
    }
  });
  if (index >= 0 && index < updatevideo.value.length) {
    updatevideo.value.splice(index, 1);
    queryData.value.files.splice(index, 1);
  }
};

// 删除_音频预览
const del_upaudio = (index) => {
  if (index >= 0 && index < updateAudio.value.length) {
    updateAudio.value.splice(index, 1);
    queryData.value.files.splice(index, 1);
  }
};

// 删除_图片预览
const del_upImage = (index) => {
  if (index >= 0 && index < updateImage.value.length) {
    updateImage.value.splice(index, 1);
    queryData.value.files.splice(index, 1);
  }
};

// 文案相关
const dynamicValidateForm = reactive({
  users: [
    {
      name: "",
    },
  ],
});

const isNameEmpty = computed(() => {
  return dynamicValidateForm.users.some((user) => !user.name);
});

// 文案 添加
const addForm = () => {
  dynamicValidateForm.users.push({
    name: "",
  });
};

// 文案 删除
const removeUser = (item) => {
  if (dynamicValidateForm.users.length <= 1) {
    return;
  }
  let index = dynamicValidateForm.users.indexOf(item);
  if (index !== -1) {
    dynamicValidateForm.users.splice(index, 1);
  }
};

const visiblePreview = ref(false);
const fileData = ref([]);

const previewClick = (data) => {
  fileData.value = data;
  visiblePreview.value = true;
};

// 重新上传

const isTen = ref(true);
const isUploadComplete = ref(false);
const fileMaxSize = ref("");
const free_send_text = ref("");
const fileMaxSizeErr = ref("");
const noenzu = ref(false);

// const getaliinfo = async () => {
//   await request
//     .get("/work_ai", "/material/upload/info", {
//       merchant_folder_statck_id: props.fileData.id,
//       upload_from: "",
//       number: "1",
//     })
//     .then((res) => {
//       // 判断 点数是否够   不够的话就停止后面操作
//       if (res.code == 1001) {
//         noenzu.value = true;
//       }

//       if (res.result) {
//         if (res.result.pointInfo.current >= res.result.pointInfo.consumes) {
//           SetUploadPath.value = res.result.upload_path;
//           fileMaxSize.value = res.result.fileMaxSize;
//           free_send_text.value = res.result.free_send_text;
//           fileMaxSizeErr.value = res.result.fileMaxSizeErr;
//         } else {
//           message.error(res.result.remainingCapacityErr);
//           // message.error(`${res.result.pointInfo.name}不足, 请充值`);
//           noenzu.value = true;
//           emits('topUp')
//         }
//       }
//     })
//     .catch((error) => {
//     });
// };

// watch(
//   () => props.visible,
//   (val) => {
//     if (val && isAlionline) {
//       getaliinfo();
//     }
//   },
//   {
//     immediate: true,
//   }
// );

// 进度条
watch(
  () => store.state.user.uploadProgress,
  (val) => {
    switch (props.type) {
      case "image":
        updateImage.value.forEach((v1) => {
          val.forEach((v2) => {
            if (v1.name == v2.filename) {
              v1.uploadProgress = v2.uploadProgress;
            }
          });
        });
        break;
      case "video":
        updatevideo.value.forEach((v1) => {
          val.forEach((v2) => {
            if (v1.name == v2.filename) {
              v1.uploadProgress = v2.uploadProgress;
            }
          });
        });
        break;
      case "audio":
        updateAudio.value.forEach((v1) => {
          val.forEach((v2) => {
            if (v1.name == v2.filename) {
              v1.uploadProgress = v2.uploadProgress;
            }
          });
        });
        break;
    }
  },
  {
    immediate: true,
    deep: true,
  }
);

// 删除的监听
watch(
  () => store.state.user.updataList,
  (val) => {
    if (val) {
      const uidsInVal = new Set(val.map((v2) => v2.uid));
      const filesToRemove = queryData.value.files.filter(
        (item) => !uidsInVal.has(item.uid)
      );
    }
  },
  {
    deep: true,
  }
);
</script>

<style lang="less" scoped>
:deep(.model_upload) {
  height: 165px !important;
  width: 240px !important;
  border-radius: 10px !important;
  margin-right: 20px;
  background: #f8f8f8;
  border: 1px dashed #ccc;
  display: flex;
  justify-content: center;
  align-items: center;

}
:deep(.ss-upload-list-item){
    display: none !important;
  }
:deep(.ss-upload-list-picture-card) {
  display: none !important;
}

.model_upload_text {
  color: #999;
  font-size: 14px;

  .model_upload_top {
    display: flex;
    justify-content: center;
    margin-top: 27px;
    align-items: center;
  }

  .model_upload_bottom {
    margin: 10px auto;
    width: 209px;
  }
}

.isupdating {
  height: 165px;
  width: 240px;
  border-radius: 10px;
  background-color: #fff;
  border: 1px dashed #d9d9d9;
  color: #999;
  font-size: 16px;
  text-align: center;
  padding-top: 60px;
  margin-right: 20px;
}

.isupdating:hover {
  border: 1px dashed #3261fb;
}

.updatevideo_All {
  margin-right: 20px;
  margin-bottom: 10px;
  width: 240px;
}

.updatevideo_item {
  height: 165px;
  width: 240px;
  background-color: #000;
  border-radius: 10px;
  cursor: pointer;
  display: flex;
  justify-content: center;
  // align-items: center;
  position: relative;

  .up_fin {
    position: absolute;
    bottom: 10px;
    right: -8px;
  }

  .updatevideo_item_s {
    width: 100%;
  }
}

.updatevideo_bottom {
  display: flex;
  justify-content: space-between;

  .updatevideo_bottom_left {
    width: 80%;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
}

.updatevideo_icon_right {
  font-size: 16px;
  margin-right: 20px;
}

.play_video {
  color: #fff;
  font-size: 33px;
  position: absolute;
  top: 43%;
}

.big-box {
  height: 390px;
  overflow-y: auto;
  display: flex;
  flex-wrap: wrap;
}

.select_icon {
  font-size: 16px;
  margin-left: 10px;
}

.line {
  height: 1px;
  width: 760px;
  background-color: #e5e5e5;
  margin: 10px 0 20px 0;
}

.text-content {
  height: 320px;
  overflow: auto;
}

.see_img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 8px;
}

.btn_btn {
  margin-bottom: 6px;
  border-radius: 6px;
  color: #fff;
  border: none;
}

.baseModel {
  :deep(.ss-modal-footer) {
    border-top: none !important;
  }

  :deep(.ss-modal-body) {
    padding-top: 30px !important;
  }

  :deep(.ss-modal) {
    width: 410px !important;
  }
}
</style>
